package demo06.hw4_28_9;

import demo02.tools.Const;
import demo04.personOperation.tool.ConnectionTool;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DAO {
    public static void insertObject(Object object){

        Connection conn = null;
        PreparedStatement ps = null;

        Class objClass = object.getClass();

        String tableName = objClass.getSimpleName();
        Field[] fields = objClass.getDeclaredFields();

        try {
            Class.forName(Const.DRIVER);

            conn = DriverManager.getConnection(Const.URL_TEST, Const.USERNAME, Const.PASSWORD);

            StringBuffer sb = new StringBuffer("insert into "+tableName.toLowerCase()+" values(");

            for (int i = 1; i <= fields.length ; i++) {
                sb.append(i==fields.length?"?)":"?,");
            }
            System.out.println(sb.toString());

            ps = conn.prepareStatement(sb.toString());

            for (int i = 0; i < fields.length ; i++) {
                Field currentField = fields[i];
                currentField.setAccessible(true);
                Object fieldValue = currentField.get(object);
                ps.setObject(i+1,fieldValue);
            }

            int result = ps.executeUpdate();
            System.out.println(result);

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            ConnectionTool.closed(conn,ps);
        }
    }

    public static <T> List<T> getList(Class<T> clazz) {
        String tableName = clazz.getSimpleName().toLowerCase();
        String sql = "SELECT * FROM " + tableName;
        return query(sql, clazz);
    }

    public static <T> List<T> query(String sql, Class<T> clazz, Object... params) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<T> resultList = new ArrayList<>();

        try {
            Class.forName(Const.DRIVER);
            conn = DriverManager.getConnection(Const.URL_TEST, Const.USERNAME, Const.PASSWORD);

            ps = conn.prepareStatement(sql);

            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }

            rs = ps.executeQuery();

            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            while (rs.next()) {

                T obj = clazz.getDeclaredConstructor().newInstance();

                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnLabel(i);
                    Object value = rs.getObject(i);

                    try {
                        Field field = clazz.getDeclaredField(columnName);
                        field.setAccessible(true);

                        if (value != null) {
                            field.set(obj, value);
                        }
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    }
                }
                resultList.add(obj);
            }
        } catch (Exception e) {
            throw new RuntimeException("查询数据失败", e);
        } finally {
            ConnectionTool.closed(conn, ps, rs);
        }
        return resultList;
    }


    public static void main(String[] args) {

        Student stu = new Student(1,"tom",18);
        insertObject(stu);

        List<Student> students = getList(Student.class);
        for (Student s : students) {
            System.out.println(s.getId() + ", " + s.getStuName() + ", " + s.getAge());
        }

        String sql = "SELECT * FROM student WHERE age > ?";
        List<Student> olderStudents = query(sql, Student.class, 15);
        for (Student s : olderStudents) {
            System.out.println(s.getId() + ", " + s.getStuName() + ", " + s.getAge());
        }
    }
}
